#include"stdafx.h"
#include "WeChatGroupZYZ.h"
#include "WeChatMasterAcc.h"
#include "WeChatNormalAcc.h"
#include"accountZYZ.h"
extern accountZYZ currAccount;
extern chatGroupZYZ* currGroup;

void WeChatGroupZYZ::write2File()
{
		std::string path = SERVICE_DIR + WeChatGroupZYZ::serviceName + 
			"/groups/" + std::to_string(this->groupID);
		std::ofstream file;
		file.open(path + INFO_FILE);
		if (!file.is_open())
		{
			_mkdir(path.c_str());
			file.open(path + INFO_FILE);
		}

		file << "name: " << this->groupName << std::endl;
		file << "ID: " << this->groupID << std::endl;
		file << "Master: " << this->masterID << std::endl;
		file << "members: " << memberIDs.size() << std::endl;

		for (auto i : this->memberIDs)
		{
			file << i << std::endl;
		}
		file.close();
}

WeChatGroupZYZ* WeChatGroupZYZ::getGroup(int ID)
{
	if (WeChatGroupZYZ::findGroup(ID))
	{
		std::ifstream file;
		file.open(SERVICE_DIR + WeChatGroupZYZ::serviceName + 
			"/groups/" + std::to_string(ID) + INFO_FILE);
		if (!file.is_open())
			throw("???");
		std::string gName, tmp;
		int gID, masterID, cnt, id;
		std::vector<int> adminID;
		std::set<int>memID;

		file >> tmp >> gName;
		file >> tmp >> gID;
		file >> tmp >> masterID;
		file >> tmp >> cnt;

		for (int i = 0; i < cnt; i++)
		{
			file >> id;
			memID.insert(id);
		}
		file.close();
		return new WeChatGroupZYZ(gID, gName, masterID, memID);
	}
	else
		throw("groupNotFound Exception");
}

bool WeChatGroupZYZ::findGroup(int ID)
{
	std::ifstream file;
	file.open(SERVICE_DIR + WeChatGroupZYZ::serviceName + 
		"/groups/" + std::to_string(ID) + INFO_FILE);

	if (file.is_open())
	{
		file.close();
		return true;
	}
	else
		return false;
}

accountStateZYZ* WeChatGroupZYZ::getState()
{
	if (currGroup->masterID == currAccount.accountID)
	{
		return new WeChatMasterAcc();
	}
	return new WeChatNormalAcc();
}

WeChatGroupZYZ::WeChatGroupZYZ(int gID, std::string gName, 
	int masterID, std::set<int> memberID)
{
	this->groupID = gID;
	this->groupName = gName;
	this->masterID = masterID;
	this->memberIDs = memberID;
}

WeChatGroupZYZ::WeChatGroupZYZ()
{
	groupID = 1000;
	groupName = "default";
}
